import os
import datetime
import logging
from logging.handlers import RotatingFileHandler

# 日志级别    数值
# CRITICAL    50
# ERROR       40
# WARNING     30
# INFO        20
# DEBUG       10
# NOTSET       0


class LoggingConfig:
    BASE_DIR = os.getcwd()
    LOGS_DIR = os.path.join(BASE_DIR, "logs")

    def setup_logging(self):
        if not os.path.exists(self.LOGS_DIR):
            os.makedirs(self.LOGS_DIR)

        self.fileHandler = logging.FileHandler(
            os.path.join(self.LOGS_DIR, "management.log"), encoding="UTF-8"
        )
        self.fileHandler.setLevel(logging.DEBUG)
        file_formatter = logging.Formatter(
            "%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s"
        )
        self.fileHandler.setFormatter(file_formatter)

        self.rotatingFileHandler = RotatingFileHandler(
            os.path.join(self.LOGS_DIR, "message1.log"),
            maxBytes=100 * 1024 * 1024,
            backupCount=10,
            encoding="UTF-8",
        )
        self.rotatingFileHandler.setLevel(logging.DEBUG)
        rotating_formatter = logging.Formatter(
            "时间:%(asctime)-15s 日志级别:%(levelname)s 文件名:%(filename)s 函数名:%(funcName)s 行数:%(lineno)d 进程号:%(process)d 当前线程号:%(thread)s 日志信息:%(message)s"
        )
        self.rotatingFileHandler.setFormatter(rotating_formatter)

        self.consoleHandler = logging.StreamHandler()
        self.consoleHandler.setLevel(logging.DEBUG)
        console_formatter = logging.Formatter(
            "%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - 进程号:%(process)d 当前线程号:%(thread)s - %(message)s"
        )
        self.consoleHandler.setFormatter(console_formatter)

        # 创建一个logger对象，并设置其级别
        self.logger = logging.getLogger("myLog")
        self.logger.setLevel(logging.DEBUG)

        # 添加handlers到logger
        self.logger.addHandler(self.fileHandler)
        self.logger.addHandler(self.rotatingFileHandler)
        self.logger.addHandler(self.consoleHandler)


if __name__ == "__main__":
    config = LoggingConfig()
    config.setup_logging()

    # 使用config.logger来记录日志
    try:
        config.logger.info("info message：输出 m =1/0")
        m = 1 / 0
    except Exception as e:
        config.logger.error("error message: %s", str(e))
